package cn.wjssl.domain.strategy.service.rule.tree.impl;

import cn.wjssl.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.wjssl.domain.strategy.service.rule.tree.ILogicTreeNode;
import cn.wjssl.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 次数锁节点
 */
@Slf4j
@Component("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTreeNode {

    // 抽奖次数
    private Long userRaffleCount = 1L;

    @Override
    public DefaultTreeFactory.TreeActionEntity logicTree(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-次数锁 userId:{} strategyId:{} awardId:{} ruleValue:{}", userId, strategyId, awardId, ruleValue);

        // 先判断规则树的配置正不正确
        long raffleCount = 0L;
        try {
            raffleCount = Long.parseLong(ruleValue);
        } catch (Exception e) {
            throw new RuntimeException("规则过滤-次数锁异常 ruleValue: " + ruleValue + " 配置不正确");
        }

        /**
         * 对比抽奖次数 和 rule_lock对应的解锁次数 rule_value
         * 如果 满足抽奖次数, ALLOW 就继续下一个节点, 也就是 stock 节点的过滤
         * 要不然就直接TAKE_OVER, 去rule_lock_award 节点
         */
        if (userRaffleCount >= raffleCount) {
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                    .build();
        }

        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .build();

    }
}
